package cn.xxstudy.visitshop.ui.activity.main.fragment.interview

import android.content.Intent
import android.view.MenuItem
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.adapter.InterviewAdapter
import cn.xxstudy.visitshop.base.adapter.OnItemClickListener
import cn.xxstudy.visitshop.base.fragment.LazyFragment
import cn.xxstudy.visitshop.ui.activity.interview.InterviewDetailActivity
import cn.xxstudy.visitshop.ui.activity.main.fragment.interview.model.InterviewData
import cn.xxstudy.visitshop.ui.activity.main.fragment.interview.viewmodel.InterviewViewModel
import cn.xxstudy.visitshop.ui.activity.visit.VisitDetailActivity
import cn.xxstudy.visitshop.util.INTERVIEW_KEY
import cn.xxstudy.visitshop.util.VISIT_KEY
import cn.xxstudy.visitshop.util.configAppearance
import kotlinx.android.synthetic.main.fragment_interview.*
import kotlinx.android.synthetic.main.fragment_visit.*
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.coroutines.launch

/**
 * @author ：DELL on 2021/3/23 .
 * @packages cn.xxstudy.visitshop.ui.activity.main.fragment.interview
 * @TODO: 拜访
 */
class InterviewFragment : LazyFragment(), Toolbar.OnMenuItemClickListener,
    SwipeRefreshLayout.OnRefreshListener, OnItemClickListener<InterviewData> {

    private lateinit var viewModel: InterviewViewModel

    override val layoutId = R.layout.fragment_interview

    override fun initView() {
        toolbarTitle.text = "拜 访"
        toolBar.inflateMenu(R.menu.menu_interview)
        toolBar.setOnMenuItemClickListener(this)
        interviewRefresh.setOnRefreshListener(this)
        interviewRefresh.configAppearance()
        interviewContent.configAppearance(context)
    }

    override fun loadData() {
        viewModel = ViewModelProvider(this).get(InterviewViewModel::class.java)

        val adapter = InterviewAdapter()
        adapter.setOnItemClickListener(this)
        interviewContent.adapter = adapter

        viewModel.interviewLiveData.observe(viewLifecycleOwner, Observer {
            adapter.datas = it
            interviewRefresh.isRefreshing = false
        })

        viewModel.failLiveData.observe(viewLifecycleOwner, Observer {
            interviewRefresh.isRefreshing = false
        })

        interviewRefresh.post {
            interviewRefresh.isRefreshing = true
            viewModel.interview("0001")
        }

    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        return false
    }

    override fun onRefresh() {
        viewModel.interview("0001")
    }

    override fun onClickItem(position: Int, data: InterviewData) {
        val intent = Intent(activity, InterviewDetailActivity::class.java)
        intent.putExtra(INTERVIEW_KEY, data)
        startActivity(intent)
    }

}